﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Web;

namespace NetCoreClass
{
    public class ipClass
    {
        public static long IPtoLong(string ip)
        {
            string[] ipA = ip.Split(new char[] { '.' });
            //long ipL = 16777216 * int.Parse(ipA[0]) + 65536 * int.Parse(ipA[1]) + 256 * int.Parse(ipA[2]) + int.Parse(ipA[3]);

            //return ipL;
            return long.Parse(ipA[0]) << 24
                    | long.Parse(ipA[1]) << 16
                    | long.Parse(ipA[2]) << 8
                    | long.Parse(ipA[3]);

        }
        public static long getLongIP(HttpContext context)
        {
            return IPtoLong(getRealIP(context));

        }
        public static string getRealIP(HttpContext context)
        {
            string user_IP = context.Connection.RemoteIpAddress.ToString();
          

            user_IP = user_IP.Replace("'", "");
            if (user_IP.IndexOf(",") > 0)
            {
                user_IP = user_IP.Substring(0, user_IP.IndexOf(","));
            }
            if (user_IP == "::1")
                user_IP = "127.0.0.1";
            return user_IP;
        }
        static String longToIp(long ip)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(ip >> 24);
            sb.Append(".");
            sb.Append((ip & 0x00FFFFFF) >> 16); sb.Append(".");
            sb.Append((ip & 0x0000FFFF) >> 8); sb.Append(".");
            sb.Append((ip & 0x0000FF));

            return sb.ToString();
        }


    }
}
